﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ContactSMS.Client.Models;
using ContactSMS.Client.Service;
using ContactSMS.Client.Views;
using System.Collections.ObjectModel;

namespace ContactSMS.Client.ViewModels
{
    public partial class MessageViewModel : ObservableObject
    {
        [ObservableProperty]
        public ObservableCollection<MessageModel> messages = new ObservableCollection<MessageModel>();
        [ObservableProperty]
        public ObservableCollection<MessageSessionModelNew> messagess = new ObservableCollection<MessageSessionModelNew>();
        private readonly MessageService messageService;

        public MessageViewModel(MessageService messageService)
        {
            this.LoadMessages();
            this.messageService = messageService;
        }

        public async Task LoadMessageSessions(int page = 1, int pageSize = 15)
        {
            try
            {
                var result = await messageService.GetMessageSessionsAsync(page, pageSize);
                if (result != null && result.Success)
                {
                    Messagess = new ObservableCollection<MessageSessionModelNew>(result.Data.List);
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", result?.Message ?? "Failed to load contacts", "OK");
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }

        private void LoadMessages()
        {
            for (int i = 0; i < 15; i++)
            {
                long id = i + 1;
                var message = new MessageModel()
                {
                    Id = id,
                    Title = "联系人" + id,
                    Desc = "描述" + id,
                    Date = "18/8",
                    Avatar = "/contact/avatar.png"
                };
                Messages.Add(message);
            }
        }

        [RelayCommand]
        public async Task NavigateToDetail(long Id)
        {
            //await Shell.Current.GoToAsync(nameof(MessageDetailPage));
            await Shell.Current.GoToAsync($"{nameof(MessageDetailPage)}?Id={Id}");
        }
    }
}
